package com.exam.servlet;

import com.alibaba.fastjson2.JSON;
import com.exam.domain.entity.User;
import com.exam.service.UserService;
import com.exam.service.impl.UserServiceImpl;
import com.exam.util.BaseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/user/*",asyncSupported = true)
public class UserServlet extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        // 手动实例化服务类
        System.out.println("手动实例化服务类");
        userService = new UserServiceImpl();  // 在这里模拟 Spring 中的依赖注入
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI(); // 获取请求的URI

        if (path.endsWith("/login")) {
//            req.startAsync();
            // 获取用户名和密码
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            BaseResult<User> result = userService.login(username, password);
            if(result.getCode()==200){
                req.getSession().setAttribute("user",result.getData());
            }
            // 处理登录请求
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);

            req.getAsyncContext().complete();

        } else if (path.endsWith("/register")) {
            // 处理注册请求
        } else {
            // 其他处理逻辑
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPut(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDelete(req, resp);
    }


}
